<template>
  <div
    class="com-global-drag-view"
    :style="{ width: `${width}px`, height: `${height}px`, left: `${boxPosition.x}px`, top: `${boxPosition.y}px` }"
    ref="ComGlobalDragView"
    @touchstart="touchstart"
    @touchmove.prevent="touchmove"
    @touchend="touchend">
    <slot/>
  </div>
</template>

<script>
  export default {
    name: "ComGlobalDragView",
    props: {
      width: {
        type: Number,
        default: 100
      },
      height: {
        type: Number,
        default: 100
      },
      left: {
        type: Number,
        default: 100
      },
      top: {
        type: Number,
        default: 100
      },
      topArea: {
        type: Number,
        default: 46
      },
      leftArea: {
        type: Number,
        default: 0
      },
      rightArea: {
        type: Number,
        default: 0
      },
      bottomArea: {
        type: Number,
        default: 0
      }
    },
    data(){
      return {
        /**
         * 向下按的位置
         */
        downPosition: {
          x: 0,
          y: 0,
          offX: 0,
          offY: 0
        },
        /**
         * 盒子的位置
         */
        boxPosition: {
          x: 0,
          y: 0
        },
        /**
         * 是否点击
         */
        isClick: false
      }
    },
    computed: {

    },
    methods: {
      screenWidth() {
        return document.documentElement.clientWidth
      },
      screenHeight() {
        return document.documentElement.clientHeight
      },
      touchstart(e) {
        this.isClick = true
        const touch = e.changedTouches[0]
        this.downPosition.x = touch.clientX
        this.downPosition.y = touch.clientY
        this.downPosition.offX = this.downPosition.x - this.boxPosition.x
        this.downPosition.offY = this.downPosition.y - this.boxPosition.y
      },
      touchmove(e) {
        if (!this.isClick) { return }
        const touch = e.changedTouches[0]
        let x = touch.clientX - this.downPosition.offX
        let y = touch.clientY - this.downPosition.offY
        if (x < this.leftArea) {
          x = this.leftArea
        } else {
          const maxX = this.screenWidth() - this.rightArea - this.width
          if (x > maxX) {
            x = maxX
          }
        }
        if (y < this.topArea) {
          y = this.topArea
        } else {
          const maxY = this.screenHeight() - this.bottomArea - this.height
          if (y > maxY) {
            y = maxY
          }
        }
        this.boxPosition.x = x
        this.boxPosition.y = y
      },
      touchend() {
        this.isClick = false
      }
    },
    mounted() {
      this.boxPosition.x = this.left
      this.boxPosition.y = this.top
    }
  }
</script>

<style lang="scss" scoped>
  .com-global-drag-view {
    position: fixed;
    z-index: 1000;
  }
</style>
